package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 处理会员操作
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;


    //手机号快速登录
    @RequestMapping("/check")
    public Result login(HttpServletResponse response,@RequestBody Map map,HttpServletRequest req){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取保存的验证码
        Jedis jedis=jedisPool.getResource();
        String validateCodeInRedis = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String num = jedis.get(telephone + "num");
        if (num==null){
            num="0";
        }
        int number = Integer.parseInt(num);
        if (number>=3){
            return new Result(false,"请稍后在试!",number);
        }
        if(validateCodeInRedis != null && validateCode != null && validateCode.equals(validateCodeInRedis)){
            //验证码输入正确
            //判断当前用户是否为会员（查询会员表来确定）
            Member member = memberService.findByTelephone(telephone);
            if(member == null){
                //不是会员，自动完成注册（自动将当前用户信息保存到会员表）
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                String pass = MD5Utils.md5("111111");
                member.setPassword(pass);
                memberService.add(member);
            }
            //向客户端浏览器写入Cookie，内容为手机号
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            //将会员信息保存到Redis
            String json = JSON.toJSON(member).toString();
            jedis.setex(telephone,60*60*30,json);
            jedis.close();
            req.getSession().setAttribute("loginInfo",member);
            return new Result(true, MessageConstant.LOGIN_SUCCESS,member);
        }else{
            //String count = jedis.get(telephone + "num");
            Integer m = number + 1;
            jedisPool.getResource().setex(telephone+"num",20,m.toString());
            if(m>=3){
                //jedis.setex(telephone+"num",15,"0");
                return new Result(false,"3次机会用尽,5分钟之后在尝试",m);
            }
            jedis.close();
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR,m);
        }
    }
    //账号密码登录
    @RequestMapping("/check2Password")
    public Result check2Password(@RequestBody Map map,HttpServletRequest req){
        Jedis jedis = jedisPool.getResource();
        if (map!=null){
            try {
                String idCard = (String) map.get("idCard");
                String password = (String) map.get("password");
                password = MD5Utils.md5(password);
                Member member = memberService.findMemberByIdCardAndPwd(idCard,password);
                String phoneNumber = member.getPhoneNumber();
                //将会员信息保存到Redis
                String json = JSON.toJSON(member).toString();
                jedis.setex(phoneNumber,60*60*30,json);
                jedis.close();
                req.getSession().setAttribute("loginInfo",member);
                return new Result(true,"登录成功",member);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,"登录失败");
            }
        }else {
            return new Result(false,"登录失败");
        }
    }

    //查询数据库是否存在登录者信息，有，说明已登录，否则未登录返回false
    @RequestMapping("/findByRedis")
    public Result findByRedis(HttpServletRequest request,String telephone){
        Jedis jedis=jedisPool.getResource();
        //Cookie[] cookies = request.getCookies();
       /* String num=null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(telephone)){
                num=cookie.getName();
            }
        }*/
        String memberPhone = jedis.get(telephone);
        jedis.close();
        if (memberPhone!=null){
            try {
                Member member = memberService.findByTelephone(telephone);
                Date birthday = member.getBirthday();
                String date = DateUtils.parseDate2String(birthday, "yyyy-MM-dd");
                Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(date);
                member.setBirthday(parse);
                return new Result(true,MessageConstant.QUERY_MEMBERDATA_SUCCESS,member);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(true,MessageConstant.QUERY_MEMBERDATA_FAIL);
            }
        }else {
            return new Result(true,MessageConstant.QUERY_MEMBERDATA_FAIL);
        }

    }

    //编辑会员资料
    @RequestMapping("/edit01")
    public Result edit(@RequestBody Member member){
       if (member!=null){
           try {
               memberService.edit01(member);
               return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
           }catch (Exception e){
               e.printStackTrace();
               return new Result(false,MessageConstant.EDIT_MEMBER_FAIL);
           }
       }else {
           return new Result(false,MessageConstant.EDIT_MEMBER_FAIL);
       }
    }

    //根据会员id查询对应预约的套餐id
    @RequestMapping("/findSetmealById")
    public Result findSetmealById(String id){
        List<Map> list = memberService.findSetmealById(Integer.parseInt(id));
        return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,list);
    }

    //查询用户是否已经更新密码
    @RequestMapping("/findPasswordById")
    public Result findPasswordById(String id){
        String password=memberService.findPasswordById(id);
        if (password.equals("96e79218965eb72c92a549dd5a330112")){
            //password="111111";
            return new Result(true,"密码未修改",password);
        }else {

            return new Result(false,"密码已修改",password);
        }
    }
    //为用户设置初始密码
    @RequestMapping("/editPassword")
    public Result editPassword(@RequestBody Map map){
        try {
            String password = (String) map.get("password");
            String pass = MD5Utils.md5(password);
            map.put("password",pass);
            memberService.editPassword(map);
            return new Result(true,"设置密码成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"设置密码失败");
        }
    }
   /* //用户修改密码
    @RequestMapping("/editPwd")
    public Result editPwd(String pwd){
        if (pwd!=null){
            memberService.editPwd(pwd);
            return new Result(true,"密码修改成功");
        }
        return new Result(false,"密码修改失败");
    }*/
    //根据日期范围查询预约的套餐
    @RequestMapping("/findSetmealByIdAndDate")
    public  Result findSetmealByIdAndDate(@RequestBody Map map) throws Exception {
        //Integer.parseInt((String)map.get("id")
        List<Map> list = memberService.findSetmealByIdAndDate(map);
        return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,list);
    }

    //根据id获取会员信息
    @RequestMapping("/findMemberById")
    public Result findMemberById(String id){
        try{
            Member member = memberService.findById(Integer.parseInt(id));
            return new Result(true,MessageConstant.QUERY_MEMBERDATA_SUCCESS,member);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MEMBERDATA_FAIL);
        }
    }
    //修改绑定的手机号,并修改redis内的信息
    @RequestMapping("/edit2Telephone")
    public Result edit2Telephone(@RequestBody Map map,HttpServletRequest req){
        String id = (String) map.get("id");
        String telephone = (String) map.get("telephone");
        String code = (String) map.get("validateCode");
        //获取被修改的用户手机号
        Member member = memberService.findById(Integer.parseInt(id));
        String phoneNumber = member.getPhoneNumber();
        Jedis jedis = jedisPool.getResource();
        String checkCode = jedis.get(phoneNumber + RedisMessageConstant.SENDTYPE_GETPWD);
        //jedis.close();
        if (checkCode==null){
            return new Result(false,"验证码输入错误！");
        }
        if (checkCode.equals(code)){
            try{
                memberService.edit2Telephone(map);
                Member member1 = memberService.findById(Integer.parseInt(id));
                jedis.del(phoneNumber);
                //将会员信息保存到Redis
                String json = JSON.toJSON(member1).toString();
                jedis.setex(telephone,60*60*30,json);
                jedis.close();
                req.getSession().removeAttribute("loginInfo");
                return new Result(true,"编辑手机号成功，请重新登录");
            }catch (Exception e){
                jedis.close();
                return new Result(false,"编辑手机号失败");
            }

        }else {
            jedis.close();
            return  new Result(false,"验证码输入错误");
        }
    }
    //使用手机号进行找回密码
    @RequestMapping("/forgetPassword")
    public Result forgetPassword(@RequestBody Map map){
        String validateCode = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        Jedis jedis = jedisPool.getResource();
        String code = jedis.get(telephone + RedisMessageConstant.SENDTYPE_GETPWD);
        String id = (String) map.get("id");
        String password = (String) map.get("password");
        password = MD5Utils.md5(password);
        if (code.equals(validateCode) && code!=null && validateCode!=null){
            try {
                memberService.forgetPassword(id,password);
                return new Result(true,"密码修改成功！");
            }catch (Exception e){
                return new Result(false,"密码修改失败！");
            }
        }else {
            return new Result(false,"密码修改失败！");
        }
    }
}
